/**
 * 应用状态追踪器
 * 用于实时追踪应用的生成状态
 */

import { ref, type Ref } from 'vue'
import { getApplicationStatus, convertStatusStringToNumber } from '@/services/appExperienceService'
import { GENERATE_STATUS } from '@/constants/appStatus'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

interface StatusTrackerOptions {
  appId: string | number
  interval?: number // 轮询间隔，默认2秒
  autoStop?: boolean // 是否在完成/失败/中断时自动停止
  onStatusChange?: (status: string) => void // 状态变化回调
  onError?: (error: any) => void // 错误回调
}

export class AppStatusTracker {
  private appId: string | number
  private interval: number
  private autoStop: boolean
  private onStatusChange?: (status: string) => void
  private onError?: (error: any) => void

  private timer: number | null = null
  private isTracking = false
  private currentStatus: string = ''

  constructor(options: StatusTrackerOptions) {
    this.appId = options.appId
    this.interval = options.interval || 2000 // 默认2秒
    this.autoStop = options.autoStop !== false // 默认自动停止
    this.onStatusChange = options.onStatusChange
    this.onError = options.onError
  }

  /**
   * 开始追踪状态
   */
  async start(): Promise<void> {
    if (this.isTracking) {
      console.warn('状态追踪器已经在运行中')
      return
    }

    // 检查登录状态
    const loginUserStore = useLoginUserStore()
    if (!loginUserStore.loginUser?.id) {
      console.warn('用户未登录，无法开始状态追踪')
      if (this.onError) {
        this.onError(new Error('用户未登录'))
      }
      return
    }

    this.isTracking = true

    // 立即获取一次状态
    await this.fetchStatus()

    // 只有在状态追踪未被停止的情况下才开始定时轮询
    if (this.isTracking) {
      this.timer = window.setInterval(async () => {
        // 在每次轮询前再次检查登录状态
        const currentLoginUser = useLoginUserStore().loginUser
        if (!currentLoginUser?.id) {
          console.warn('用户已退出登录，停止状态追踪')
          this.stop()
          return
        }

        await this.fetchStatus()
      }, this.interval)
    }

    // console.log(`开始追踪应用 ${this.appId} 的状态，间隔 ${this.interval}ms`)
  }

  /**
   * 停止追踪状态
   */
  stop(): void {
    if (!this.isTracking) {
      return
    }

    if (this.timer) {
      window.clearInterval(this.timer)
      this.timer = null
    }

    this.isTracking = false

    // console.log(`停止追踪应用 ${this.appId} 的状态`)
  }

  /**
   * 获取状态
   */
  private async fetchStatus(): Promise<void> {
    try {
      const res = await getApplicationStatus(this.appId)

      if (res.data.code === 0 && res.data.data) {
        // 将字符串状态转换为数字
        const numericStatus = convertStatusStringToNumber(res.data.data)
        const newStatus = numericStatus.toString()
        const oldStatus = this.currentStatus

        // 更新内部状态
        this.currentStatus = newStatus

        // 如果状态发生变化，触发回调
        if (newStatus !== oldStatus && this.onStatusChange) {
          this.onStatusChange(newStatus)
        }

        // 检查是否需要自动停止
        if (this.autoStop && this.shouldStopTracking(newStatus)) {
          this.stop()
        }
      } else {
        // 检查是否是认证错误（未登录）
        const isAuthError = res.data.code === 40100 || res.data.message?.includes('未登录')

        if (isAuthError) {
          console.warn('用户未登录，停止状态追踪')
          this.stop() // 立即停止轮询
          if (this.onError) {
            this.onError(new Error('用户未登录'))
          }
          return
        }

        console.error('获取应用状态失败:', res.data.message)
        if (this.onError) {
          this.onError(new Error(res.data.message || '获取状态失败'))
        }

        // 对于非认证错误，也应该考虑停止轮询，避免无限重试
        if (res.data.code !== 0) {
          console.warn('获取状态失败，停止轮询以避免无限重试')
          this.stop()
        }
      }
    } catch (error: any) {
      console.error('获取应用状态异常:', error)

      // 检查是否是网络错误或认证错误
      if (error?.response?.status === 401 || error?.response?.status === 403) {
        console.warn('认证失败，停止状态追踪')
        this.stop()
      } else if (error?.code === 'NETWORK_ERROR' || error?.message?.includes('Network Error')) {
        console.warn('网络错误，停止状态追踪')
        this.stop()
      }

      if (this.onError) {
        this.onError(error)
      }
    }
  }  /**
   * 获取当前状态
   */
  getCurrentStatus(): string {
    return this.currentStatus
  }

  /**
   * 判断是否应该停止追踪
   */
  private shouldStopTracking(status: string): boolean {
    const numStatus = parseInt(status)
    return (
      numStatus === GENERATE_STATUS.COMPLETED ||
      numStatus === GENERATE_STATUS.FAILED ||
      numStatus === GENERATE_STATUS.INTERRUPTED
    )
  }

  /**
   * 销毁追踪器
   */
  destroy(): void {
    this.stop()
    this.onStatusChange = undefined
    this.onError = undefined
  }

  /**
   * 获取当前追踪状态
   */
  get tracking(): boolean {
    return this.isTracking
  }
}

/**
 * 创建应用状态追踪器的工厂函数
 */
export function createAppStatusTracker(options: StatusTrackerOptions): AppStatusTracker {
  return new AppStatusTracker(options)
}

/**
 * 状态追踪 Composable
 */
export function useAppStatusTracker(appId: string | number) {
  const tracker = ref<AppStatusTracker | null>(null)

  // 创建独立的响应式状态
  const status = ref('')
  const isLoading = ref(false)

  const startTracking = async (options?: Partial<StatusTrackerOptions>) => {
    if (tracker.value) {
      tracker.value.destroy()
    }

    tracker.value = new AppStatusTracker({
      appId,
      ...options,
      onStatusChange: (newStatus: string) => {
        status.value = newStatus
        // 调用用户提供的回调
        if (options?.onStatusChange) {
          options.onStatusChange(newStatus)
        }
      },
      onError: (error: any) => {
        isLoading.value = false
        // 调用用户提供的回调
        if (options?.onError) {
          options.onError(error)
        }
      }
    })

    if (tracker.value) {
      isLoading.value = true
      await tracker.value.start()
    }
  }

  const stopTracking = () => {
    if (tracker.value) {
      tracker.value.stop()
      isLoading.value = false
    }
  }

  const destroyTracker = () => {
    if (tracker.value) {
      tracker.value.destroy()
      tracker.value = null
    }
    status.value = ''
    isLoading.value = false
  }

  return {
    tracker,
    startTracking,
    stopTracking,
    destroyTracker,
    status,
    isLoading,
  }
}
